package com.yociyy.gate.filter;

import cn.hutool.core.util.StrUtil;
import com.yociyy.sms.exception.ValidateCodeException;
import com.yociyy.sms.validate.code.ValidateCodeProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 验证码过滤器
 *
 * @author: YoCiyy
 * @date: 2020/5/25
 */
@Component
public class ValidateCodeFilter extends AbstractGatewayFilterFactory<ValidateCodeFilter.Config> {

	@Autowired
	private Map<String, ValidateCodeProcessor> validateCodeProcessors;

	public ValidateCodeFilter() {
		// 这里需要将自定义的config传过去，否则会报告ClassCastException
		super(Config.class);
	}

	@Override
	public String name() {
		return "ValidateCode";
	}

	@Override
	public List<String> shortcutFieldOrder() {
		return Arrays.asList("enabled");
	}

	@Override
	public GatewayFilter apply(Config config) {
		return (exchange, chain) -> {
			if (!config.isEnabled()) {
				return chain.filter(exchange);
			}

			HttpServletRequest request = (HttpServletRequest) exchange.getRequest();
			HttpServletResponse response = (HttpServletResponse) exchange.getResponse();

			if (StrUtil.equals("auth/login", request.getRequestURI())) {
				try {
					// 校验验证码请求
					validate(new ServletWebRequest(request, response));
				} catch (ValidateCodeException e) {
				}
			}
			return chain.filter(exchange);
		};
	}

	public static class Config {
		// 控制是否开启验证码过滤器
		private boolean enabled;

		public Config() {
		}

		public boolean isEnabled() {
			return enabled;
		}

		public void setEnabled(boolean enabled) {
			this.enabled = enabled;
		}
	}

	/**
	 * 验证码校验
	 * 
	 * @param request
	 */
	public void validate(ServletWebRequest request) {
//		validateCodeProcessors.get(ValidateCodeType.IMAGE + "CodeProcessor").validate(request);
	}
}
